//
//  AppDelegate.swift
//  XKWeibo
//
//  Created by 小k on 15/11/3.
//  Copyright © 2015年 小k. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        setAppearance()
        
        // 创建window
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window?.backgroundColor = UIColor.whiteColor()
        
        // 设置窗口的根控制器
        window?.rootViewController = defaultRootViewController
        
        // 显示窗口
        window?.makeKeyAndVisible()
    
        
        // 注册通知
        NSNotificationCenter.defaultCenter().addObserverForName(WBSwitchRootViewController,
            object: nil,
            queue: nil)
            { [weak self] (notification) -> Void in
                print(notification)
                
                let vc = notification.object != nil ? XKWelcomeViewController() : MainViewController()
                
                // 切换控制器
                self?.window?.rootViewController = vc
        }
        
        
        return true
    }

    // 注销通知
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self, name: WBSwitchRootViewController, object: nil)
    }
    
    
    
    // 设置全局外观

    private func setAppearance () {
        UINavigationBar.appearance().tintColor = WBAppearanceTintColor
        UITabBar.appearance().tintColor = WBAppearanceTintColor
        
//        print(XKUserAccountViewModel.sharedUserAccount.account)

    }
   
}


// MARK: - 界面切换
extension AppDelegate {
    
    /// 默认控制器
    private var defaultRootViewController:UIViewController {
        if XKUserAccountViewModel.sharedUserAccount.userLogin {
            return isNewVersion ? XKNewFeatureViewController () : XKWelcomeViewController()
        }
        return MainViewController ()
    }
    
    
    /// 是否有新版
    private var isNewVersion:Bool {
        // 1. 获取当前版本
        let currentVersion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
        let version = Double(currentVersion)!
        
        
        // 2.从沙河中获取之前保存的版本
        let sandboxVersionKey = "sandboxVersionKey"
        let snadboxVersion = NSUserDefaults.standardUserDefaults().doubleForKey(sandboxVersionKey)
        
        // 3. 将当前版本保存到沙河
        NSUserDefaults.standardUserDefaults().setDouble(version, forKey: sandboxVersionKey)
        
        // 4. 返回比较结果
        return version > snadboxVersion
    }
  
}
